#coding:utf-8
import hashlib
import os
import time
from sevencow import Cow, CowException


class Qiniu:
    def __init__(self, bucket):
        access_key = 't3HDvmNGbqkNlzmS7CpukBBk_tJh4OYuVlA6Gs1t'
        secret_key = 'JB-8rRpVgV6HgEUOPUW6QK0GshGxUCcNoPQiLwJU'

        cow = Cow(access_key, secret_key)

        #空间&&域名映射表
        bucket_domain = {
            'mt-temp': 'http://mt-temp.qiniudn.com/',
            'mt-avatar': 'http://mt-avatar.qiniudn.com/',
            'mt-share': 'http://mt-share.qiniudn.com/',
            'mt-card': 'http://mt-card.qiniudn.com/',
            'mt-other': 'http://mt-other.qiniudn.com/',
        }

        self.domain = bucket_domain[bucket] or None
        self.bucket = bucket
        self.cow = cow
        self.bucket_domain = bucket_domain

    #上传文件
    def upload(self, source):
        bucket = self.cow.get_bucket(self.bucket)
        #保存到服务器上的路径
        save_path = time.strftime('%Y/%m/%d', time.localtime(time.time()))
        file_name = ''
        full_path = ''
        ext_name = ''

        #source为字符串时为文件路径
        if isinstance(source, basestring):
            file_name = source
            full_path = source
        else:
            file_name = source.name
            full_path = source.file.name

        #获取原图的路径&&扩展名
        ext_name = os.path.splitext(file_name)[1]
        #保存到服务器的文件名
        bucket_path = '%s/%s%s' % (save_path,
                                   hashlib.new('md5', '%s%s' % (file_name, time.time())).hexdigest(),
                                   ext_name)
        img_data = bucket.put(full_path, names={full_path: bucket_path})

        #删除临时文件
        try:
            os.unlink(full_path)
        finally:
            return {'path': '%s%s' % (self.domain, bucket_path)}

    #移动文件
    def move(self, source, tar_bucket):
        domain = self.bucket_domain[tar_bucket]
        if domain:
            source_path = source.replace(self.domain, '')

            self.cow.move([self.bucket, source_path, tar_bucket, source_path])

            return '%s%s' % (domain, source_path)
        return None

    #保存远程图片
    def save_remote(self, remote, tar_bucket):
        domain = self.bucket_domain[tar_bucket]
        if domain:
            #保存到服务器上的路径
            save_path = time.strftime('%Y/%m/%d', time.localtime(time.time()))
            bucket_path = '%s/%s.jpg' % (save_path, hashlib.new('md5', '%s%s' % (remote, time.time())).hexdigest())

            try:
                self.cow.fetch_remote(remote, tar_bucket, bucket_path)
                return '%s%s' % (domain, bucket_path)
            except CowException as e:
                pass

        return None

    #删除文件
    def delete(self, path):
        bucket = self.cow.get_bucket(self.bucket)
        #删除原图
        if path.find(self.domain) > -1:
            try:
                self.cow.delete(self.bucket, path.replace(self.domain, ''))
            except CowException as e:
                pass

    #获取图片属性
    def get_imageinfo(self, source):
        data = self.cow.get_imageinfo(source)

        print data

if __name__ == "__main__":
    Qiniu('mt-share').get_imageinfo('http://mt-share.qiniudn.com/2014/04/21/74dba597cbb42c047ce78c0094a7ba58.jpg')
